<template>
  <div class="images-container" :class="{ 'light-theme': themeStore.isLight }">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>图片管理</span>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索图片标题或内容"
              prefix-icon="Search"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
            <el-select
              v-model="statusFilter"
              placeholder="状态筛选"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <!-- 图片列表 -->
      <el-table
        :data="imageList"
        style="width: 100%"
        v-loading="loading"
        border
        :fit="true"
        class="compact-table"
        size="small"
        :cell-class-name="tableCellClassName"
        row-class-name="compact-row"
      >
        <!-- 序号 -->
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>

        <!-- 图片显示 -->
        <el-table-column label="图片" width="80">
          <template #default="scope">
            <div class="image-cell">
              <el-image
                style="width: 50px; height: 50px; object-fit: cover;"
                :src="scope.row.url"
                :preview-src-list="[scope.row.url]"
                preview-teleported
                fit="cover"
                class="table-image"
              />
            </div>
          </template>
        </el-table-column>

        <!-- 作者信息 -->
        <el-table-column label="作者" min-width="120">
          <template #default="scope">
            <div class="author-info">
              <el-avatar :size="20" :src="scope.row.author.avatar" class="author-avatar" />
              <span class="author-name">{{ scope.row.author.nickname }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 图片种类 -->
        <el-table-column prop="category" label="图片种类" min-width="100">
          <template #default="scope">
            <span>{{ scope.row.category || '未分类' }}</span>
          </template>
        </el-table-column>

        <!-- 拍摄设备 -->
        <el-table-column prop="device" label="拍摄设备" min-width="100">
          <template #default="scope">
            <span>{{ scope.row.device || '未知' }}</span>
          </template>
        </el-table-column>

        <!-- 上传时间 -->
        <el-table-column prop="uploaded_at" label="上传时间" width="130">
          <template #default="scope">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ formatDate(scope.row.uploaded_at) }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <div class="status-container">
              <el-tag 
                :type="{
                  0: 'warning',
                  1: 'success',
                  2: 'danger',
                  3: 'info'
                }[scope.row.status]"
                class="status-tag"
                size="small"
              >
                {{ {
                  0: '审核中',
                  1: '已发布',
                  2: '已封禁',
                  3: '已删除'
                }[scope.row.status] }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <div class="action-btn-group">
              <el-button 
                type="primary" 
                size="small" 
                @click="viewImage(scope.row)"
                text
              >
                查看
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="auditImage(scope.row)"
                :disabled="scope.row.status === 2"
                text
              >
                审核
              </el-button>
              
              <el-popconfirm
                title="确定要删除这张图片吗?"
                @confirm="deleteImageHandler(scope.row)"
              >
                <template #reference>
                  <el-button type="danger" size="small" text>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片详情对话框 -->
    <el-dialog v-model="dialogVisible" title="图片详情" width="70%">
        <div v-if="currentImage" class="image-detail">
          <div class="image-header">
            <div class="author-info">
              <el-avatar :size="40" :src="currentImage.author.avatar" />
              <span class="author-name">{{ currentImage.author.nickname }}</span>
            </div>
            <div class="upload-time">
              上传时间: {{ formatDate(currentImage.uploaded_at) }}
            </div>
          </div>
          
          <div class="image-preview">
            <el-image
              :src="currentImage.url"
              :preview-src-list="[currentImage.url]"
              preview-teleported
              fit="scale-down"
              style="width: 100%; height: 400px; object-fit: contain; background-color: #f5f7fa;"
            />
          </div>

          <el-descriptions :title="'图片信息'" :column="3" border>
            <template #extra>
              <el-button type="primary" @click="copyImageInfo" text class="copy-button">
                <el-icon><Document /></el-icon>
                复制
              </el-button>
            </template>
            <el-descriptions-item label="拍摄设备">{{ currentImage.device || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="光圈">{{ currentImage.aperture || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="焦距">{{ currentImage.focal_length || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="快门">{{ currentImage.shutter || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="ISO">{{ currentImage.iso || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="拍摄时间">{{ formatDate(currentImage.taken_at) }}</el-descriptions-item>
            <el-descriptions-item label="经度">{{ currentImage.longitude || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="纬度">{{ currentImage.latitude || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="分类">{{ currentImage.category || '未分类' }}</el-descriptions-item>
            <el-descriptions-item label="图片url">
              <a :href="currentImage.url" target="_blank" rel="noopener noreferrer">{{ currentImage.url || '未知' }}</a>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>

      <el-dialog
  v-model="auditDialogVisible"
  title="图片审核结果"
  width="40%"
>
  <div v-if="auditResult" class="audit-result">
    <el-alert
      :type="auditResult.passed ? 'success' : 'error'"
      :title="auditResult.passed ? '图片审核通过' : '图片审核不通过'"
      show-icon
      :description="`检测类型: ${getSceneTypeName(auditResult.scene)} (${auditResult.rate.toFixed(2)}%)`"
    />
    
    

    <div v-if="!auditResult.passed" class="violation-details">
      <h4>违规详情：</h4>
      <el-tag type="danger" effect="dark" class="detail-tag" v-for="detail in auditResult.details" :key="detail">
        {{ detail }}
      </el-tag>
    </div>
    <div class="audit-actions">
      <el-button 
        type="success" 
        @click="currentImage && currentImage.id ? updateImageStatus(currentImage.id, 1) : ElMessage.error('无法获取图片信息')"
        text
      >
        设为已发布
      </el-button>
      <el-button 
        type="danger" 
        @click="currentImage && currentImage.id ? updateImageStatus(currentImage.id, 2) : ElMessage.error('无法获取图片信息')"
        text
      >
        设为违规
      </el-button>
    </div>
  </div>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage} from 'element-plus'
import request from '@/utils/request'
import { useThemeStore } from '@/stores/theme'
import { Clock, Document } from '@element-plus/icons-vue'

// 表格数据
const loading = ref(false)
const imageList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const statusFilter = ref('')  // 状态筛选值
const statusOptions = [
  { value: 0, label: '审核中' },
  { value: 1, label: '已发布' },
  { value: 2, label: '已封禁' }
]

// 对话框控制
const dialogVisible = ref(false)
const auditDialogVisible = ref(false)
const currentImage = ref(null)
const auditResult = ref(null)

const themeStore = useThemeStore()

// 格式化时间函数，只显示年月日
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始，因此需要加1并确保为2位数
  const day = String(date.getDate()).padStart(2, '0') // 确保为2位数
  return `${year}-${month}-${day}`
}

const sceneTypeMap = {
  'porn': '色情',
  'terrorism': '暴恐',
  'ad': '广告',
  'live': '直播',
  'qrcode': '二维码'
}

const getSceneTypeName = (scene) => {
  return sceneTypeMap[scene] || scene
}

// 加载图片列表
const loadImageList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      excludeStatus: 3 // 排除软删除的图片
    }
    
    // 只有当选择了具体状态时才添加 status 参数
    if (statusFilter.value !== '') {
      params.status = statusFilter.value
    }

    const res = await request.get('/photo/list', { params })
    imageList.value = res.data.data.list || []
    total.value = res.data.data.total || 0
  } catch (error) {
    console.error('加载图片列表失败:', error)
    ElMessage.error('加载列表失败')
  } finally {
    loading.value = false
  }
}

// 首次加载
onMounted(() => {
  loadImageList()
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadImageList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadImageList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadImageList()
}

// 查看图片详情
const viewImage = (image) => {
  currentImage.value = image
  dialogVisible.value = true
}

// 审核图片
const auditImage = async (image) => {
  if (!image || !image.id) {
    ElMessage.error('无效的图片信息')
    return
  }
  try {
    currentImage.value = { ...image }  // 使用解构赋值来创建新对象
    const res = await request.post(`/photo/audit/${image.id}`)
    if (res.data && res.data.data) {
      auditResult.value = res.data.data
      auditDialogVisible.value = true
    } else {
      throw new Error('审核返回数据格式错误')
    }
  } catch (error) {
    console.error('审核图片失败:', error)
    ElMessage.error('审核失败：' + (error.message || '未知错误'))
    currentImage.value = null
    auditResult.value = null
  }
}

// 更新图片状态
const updateImageStatus = async (imageId, status) => {
  if (!imageId) {
    ElMessage.error('无法获取图片信息')
    return
  }
  try {
    await request.post(`/photo/status`, {
      id: imageId.toString(),
      status: status.toString()  
    })
    ElMessage.success('状态更新成功')
    auditDialogVisible.value = false
    auditResult.value = null
    currentImage.value = null
    loadImageList()
  } catch (error) {
    console.error('更新图片状态失败:', error)
    ElMessage.error('更新状态失败：' + (error.message || '未知错误'))
  }
}

// 删除图片
const deleteImageHandler = async (image) => {
  try {
    await request.delete(`/photo/delete/${image.id}`)
    imageList.value = imageList.value.filter(item => item.id !== image.id)
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除图片失败:', error)
  }
}

// 设置表格单元格class
const tableCellClassName = () => {
  return 'compact-cell'
}

// 复制图片信息
const copyImageInfo = () => {
  if (currentImage.value) {
    try {
      const imageInfo = {
        id: currentImage.value.id,
        url: currentImage.value.url,
        category: currentImage.value.category || '未分类',
        device: currentImage.value.device || '未知',
        aperture: currentImage.value.aperture || '未知',
        focal_length: currentImage.value.focal_length || '未知',
        shutter: currentImage.value.shutter || '未知',
        iso: currentImage.value.iso || '未知',
        uploaded_at: formatDate(currentImage.value.uploaded_at) || '未知',
        taken_at: formatDate(currentImage.value.taken_at) || '未知',
        longitude: currentImage.value.longitude || '未知',
        latitude: currentImage.value.latitude || '未知',
        status: currentImage.value.status,
        author: {
          nickname: currentImage.value.author.nickname,
          avatar: currentImage.value.author.avatar
        }
      }
      
      // 创建格式化文本
      let formattedInfo = '图片信息：\n';
      formattedInfo += `ID: ${imageInfo.id}\n`;
      formattedInfo += `URL: ${imageInfo.url}\n`;
      formattedInfo += `分类: ${imageInfo.category}\n`;
      formattedInfo += `拍摄设备: ${imageInfo.device}\n`;
      formattedInfo += `光圈: ${imageInfo.aperture}\n`;
      formattedInfo += `焦距: ${imageInfo.focal_length}\n`;
      formattedInfo += `快门: ${imageInfo.shutter}\n`;
      formattedInfo += `ISO: ${imageInfo.iso}\n`;
      formattedInfo += `上传时间: ${imageInfo.uploaded_at}\n`;
      formattedInfo += `拍摄时间: ${imageInfo.taken_at}\n`;
      formattedInfo += `经度: ${imageInfo.longitude}\n`;
      formattedInfo += `纬度: ${imageInfo.latitude}\n`;
      formattedInfo += `作者: ${imageInfo.author.nickname}\n`;
      
      // 使用浏览器内置Clipboard API
      navigator.clipboard.writeText(formattedInfo).then(() => {
        ElMessage.success('图片信息已复制到剪贴板')
      }).catch(() => {
        ElMessage.error('复制图片信息失败')
      });
    } catch (error) {
      console.error('复制图片信息失败:', error);
      ElMessage.error('复制图片信息失败');
    }
  }
}
</script>

<style scoped>
.images-container {
  padding: 0 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-box .el-input {
  width: 200px;
}

.search-box .el-select {
  width: 120px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.truncate-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  max-width: 350px;
}

.image-detail {
  padding: 0 20px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-name {
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.image-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.image-preview {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  overflow: hidden;
}

.image-meta {
  margin: 15px 0;
}

.meta-row {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
}

.image-exif {
  margin-top: 20px;
}

.image-exif h3 {
  margin-bottom: 15px;
}

.audit-result {
  padding: 20px 0;
}

.audit-actions {
  margin: 20px 0;
  display: flex;
  gap: 12px;
  justify-content: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.audit-actions .el-button {
  min-width: 120px;
  padding: 12px 24px;
  font-weight: 500;
}

.violation-details {
  margin-top: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.violation-details h4 {
  color: #303133;
  font-size: 16px;
  margin-bottom: 16px;
  font-weight: 600;
}

.detail-tag {
  margin: 6px;
  padding: 8px 16px;
  font-size: 13px;
}

.suggestion-box {
  margin-top: 24px;
  padding: 20px;
  background: #fffbf4;
  border-radius: 8px;
  border: 1px solid #faecd8;
}

.ban-actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.ban-actions .el-button {
  flex: 1;
  min-width: 120px;
  padding: 12px 20px;
}

.status-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.status-message {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.status-container {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
  text-align: center;
}

.image-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1px 0;
  text-align: center;
}

.images-container:not(.light-theme) .card-header > span {
  color: #fff;
  font-weight: 700;
  letter-spacing: 1px;
}

.images-container:not(.light-theme) .box-card {
  background: #23262F !important;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 rgba(80, 80, 120, 0.18);
  border: 1px solid #23262F;
}

.images-container:not(.light-theme) :deep(.el-table) {
  --el-table-border-color: #363b48;
  --el-table-header-bg-color: #23262F;
  --el-table-row-hover-bg-color: #292c36;
  --el-table-text-color: #e0e0e0;
  background-color: #23262F;
  color: #e0e0e0;
  border-color: #363b48;
}

.images-container:not(.light-theme) :deep(.el-table th) {
  background: #23262F;
  color: #e0e0e0;
  font-weight: 600;
  text-align: center;
}

.images-container:not(.light-theme) :deep(.el-table td) {
  background: #23262F;
  color: #bfcbd9;
}

.images-container:not(.light-theme) :deep(.el-table__empty-block) {
  background: #23262F;
}

.images-container:not(.light-theme) :deep(.el-table .cell) {
  color: #bfcbd9;
}

.images-container:not(.light-theme) :deep(.el-table__empty-text) {
  color: #7b8190;
  font-size: 1.1rem;
}

.images-container:not(.light-theme) .description-title {
  color: #e0e0e0;
}

.author-avatar {
  width: 20px;
  height: 20px;
}

.author-name {
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.description-header {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 4px;
}

.description-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.flex-spacer {
  flex: 1;
}

.copy-button {
  margin-left: 8px;
}

.copy-button-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.copy-button-container .el-button {
  padding: 12px 24px;
  font-size: 14px;
}
</style>
